package com.example.examsystem.controller;

import com.example.examsystem.common.PageResponse;
import com.example.examsystem.dto.QuestionImportDto;
import com.example.examsystem.service.QuestionImportService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * 试题导入控制器
 * 提供试题导入相关的RESTful API接口
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/import")
public class QuestionImportController {

    private final QuestionImportService questionImportService;

    /**
     * 获取试题模板文件
     * 模板文件为CSV格式，包含以下列：
     * 题干,选项A,选项B,选项C,选项D,正确答案,解析,难度,知识点
     * 用户下载后可另存为Excel格式进行编辑和导入
     */
    @GetMapping("/template")
    public ResponseEntity<Resource> downloadTemplate() {
        Resource resource = new ClassPathResource("templates/question-template.xlsx");
        if (!resource.exists()) {
            log.error("试题模板文件不存在");
            return ResponseEntity.notFound().build();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=question-template.xlsx");
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

    /**
     * 获取导入历史记录列表
     * @param fileName 文件名
     * @param page 页码
     * @param size 每页大小
     * @return 导入历史记录列表
     */
    @GetMapping("/history")
    @PreAuthorize("hasAuthority('question:import:view')")
    public ResponseEntity<PageResponse<QuestionImportDto>> getImportHistory(
            @RequestParam(required = false) String fileName,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResponse<QuestionImportDto> records = questionImportService.getImportHistory(page, size, fileName);
        return ResponseEntity.ok(records);
    }

    /**
     * 根据ID获取单个导入记录
     * @param id 导入记录ID
     * @return 导入记录详情
     */
    @GetMapping("/records/{id}")
    public ResponseEntity<QuestionImportDto> getImportRecord(@PathVariable Long id) {
        QuestionImportDto record = questionImportService.getImportRecord(id);
        return ResponseEntity.ok(record);
    }

    /**
     * 下载导入错误文件
     * @param id 导入记录ID
     * @param response HTTP响应对象
     * @throws IOException IO异常
     */
    @GetMapping("/records/{id}/error-file")
    @PreAuthorize("hasAuthority('question:import:download_error')")
    public void downloadErrorFile(@PathVariable Long id, HttpServletResponse response) throws IOException {
        Resource resource = questionImportService.downloadErrorFile(id);
        if (resource != null) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"error-report.xlsx\"");
            response.getOutputStream().write(resource.getInputStream().readAllBytes());
        }
    }
}